package com.snap.vseries.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.snap.vseries.AppConfig;
import com.snap.vseries.R;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.autosize.utils.AutoSizeUtils;

/**
 * @author Rachel
 */
public class ChannelLayout extends LinearLayout {
    private int[] colors = {ContextCompat.getColor(getContext(), R.color.fam), ContextCompat.getColor(getContext(), R.color.vic),
            ContextCompat.getColor(getContext(), R.color.rox), ContextCompat.getColor(getContext(), R.color.cy5)};
    private int channelLayoutWidth;

    public ChannelLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        obtainStyledAttrs(attrs);
        setOrientation(VERTICAL);
        setGravity(Gravity.CENTER);
    }

    private void obtainStyledAttrs(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ChannelLayout);
        channelLayoutWidth = typedArray.getInteger(R.styleable.ChannelLayout_width, -1);
//        mScaleStrokeWidth = typedArray.getDimension(R.styleable.DashboardProgressView_scaleStrokeWidth, AutoSizeUtils.dp2px(getContext(), 2));
//        mMaxScaleStrokeWidth = typedArray.getDimension(R.styleable.DashboardProgressView_scaleStrokeWidth, AutoSizeUtils.dp2px(getContext(), 6));
//        mPadding = typedArray.getDimension(R.styleable.DashboardProgressView_padding, AutoSizeUtils.dp2px(getContext(), 9));
//        //文字大小
//        mTextSize = typedArray.getDimension(R.styleable.DashboardProgressView_textSize, AutoSizeUtils.sp2px(getContext(), 90));
//        //文字
//        mTextColor = typedArray.getColor(R.styleable.DashboardProgressView_textColor, 0xFF202023);
        // 一定要回收
        typedArray.recycle();
    }

    public void initView(String[] contents, int channelJoinFlag) {
        List<LinearLayout> layoutList = new ArrayList<>();
        for (int i = 0; i < AppConfig.TOTAL_CHANNEL_COUNT; i++) {
            LinearLayout childLayout = newLinearLayout();
            childLayout.addView(newView(colors[i]));
            childLayout.addView(newContentView(contents[i] == null ? ("CH " + (i + 1)) : contents[i]));
            boolean enable = (channelJoinFlag >> i & 0x01) == 0x01;
            if (enable) {
                layoutList.add(childLayout);
            }
        }

        int count = 1;
        if (layoutList.size() > 2 && outOfWidth(layoutList)) {
            count = 2;
        }
        int index = 0;
        for (int j = 0; j < count; j++) {
            LinearLayout layout = newLinearLayout();
            for (int i = index; i < layoutList.size(); i++) {
                LinearLayout childLayout = layoutList.get(i);
                layout.addView(childLayout);
                index++;
                if (count != 1 && layout.getChildCount() > 1) {
                    break;
                }
            }
            addView(layout);
        }
    }

    private boolean outOfWidth(List<LinearLayout> layoutList) {
        int width = getScreenWidth() / 2;
        int row1 = getViewWidth(layoutList.get(0)) + getViewWidth(layoutList.get(1));
        if (row1 > width) {
            //Logger.i( "控件宽度" + width + "，行1宽度" + row1);
            return true;
        }
        int row2 = getViewWidth(layoutList.get(2)) + (layoutList.size() == 4 ? getViewWidth(layoutList.get(3)) : 0);
        if (row2 > width) {
            //Logger.i( "控件宽度" + width + "，行1宽度" + row1 + "，行2宽度" + row2);
            return true;
        }
        return false;
    }

    /**
     * 得到屏幕宽度
     *
     * @return
     */
    private int getScreenWidth() {
        int width;
        if (channelLayoutWidth==-1){
            WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics displayMetrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            width=displayMetrics.widthPixels - dp2px(32);
        }else {
            width=AutoSizeUtils.dp2px(getContext(),channelLayoutWidth);
        }

        return width;
    }

    private int getViewWidth(View layout) {
//        int w = View.MeasureSpec.makeMeasureSpec(245, MeasureSpec.EXACTLY);
//        int h = View.MeasureSpec.makeMeasureSpec(64, MeasureSpec.EXACTLY);
//        layout.measure(w, h);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        layout.measure(w, h);
        int width = layout.getMeasuredWidth();

        return width;
    }

    private View newView(int color) {
        View view = new View(getContext());
        view.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.bg_blue_6));
        view.getBackground().setColorFilter(color, PorterDuff.Mode.SRC);
        LayoutParams layoutParams = new LayoutParams(dp2px(12), dp2px(4));
        layoutParams.setMargins(0, 0, dp2px(8), 0);
        view.setLayoutParams(layoutParams);
        return view;
    }

    private View newContentView(String content) {
        TextView tv = new TextView(getContext());
        tv.setTextSize(12);
        tv.setText(content);
        tv.setTextColor(ContextCompat.getColor(getContext(), R.color.black666));
        tv.setGravity(Gravity.CENTER);
        LayoutParams layoutParams = new LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 0, dp2px(20), 0);
        tv.setLayoutParams(layoutParams);
        return tv;
    }

    private LinearLayout newLinearLayout() {
        LinearLayout layout = new LinearLayout(getContext());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, dp2px(24));
        layout.setGravity(Gravity.CENTER_VERTICAL);
        layout.setOrientation(HORIZONTAL);
        layout.setLayoutParams(layoutParams);
        return layout;
    }

    private int dp2px(int value) {
        return AutoSizeUtils.dp2px(getContext(), value);
    }
}
